﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.SessionState;
using System.Data;
using System.IO;
using Framework.DataAccess;
using Framework.Common.JsonEntities;
using Framework.Common;
using Framework.Common.Common;
using Mode;
using CDO;
using ADODB;
namespace WebSite.WebServer
{
    /// <summary>
    /// ExportWordHandler 的摘要说明
    /// </summary>
    public class ExportWordHandler : IHttpHandler, IReadOnlySessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            
           
                int R = 0;
                if (context.Request.Params["isApp"] != null)
                {
                Int32.TryParse(context.Request.Params["isApp"], out R);
                }
                if (R == 2)
                {
                    /*生成html文件*/
                    WriteHtml();
                }
                else
                {
                    string url = context.Request.QueryString["PageAddress"];
                    if (url.Length > 0)
                    {

                        string strTemp = convertWebPageToMHTString(url);

                        sendMHTFile(context, strTemp, HttpUtility.UrlPathEncode(context.Request.QueryString["Pname"]), context.Request.QueryString["Type"]);

                    }
                }



            }
       

        /// <summary>
        /// 写成html文件
        /// </summary>
        public void WriteHtml()
        {
            var context = System.Web.HttpContext.Current;

            string rooturl = context.Request.Url.ToString();
            if (rooturl.LastIndexOf('/') != -1)
            {
                rooturl = rooturl.Substring(0, rooturl.LastIndexOf('/'));

                if (rooturl.LastIndexOf('/') != -1)
                {

                    rooturl = rooturl.Substring(0, rooturl.LastIndexOf('/') + 1);

                }
                else
                {
                    rooturl = rooturl + "/";
                }
            }
            loginInfo login = chklogin();
            if (login != null)
            {
                StringBuilder htmlstr = new StringBuilder();
                string hdFileName = context.Request.Params["hdFileName"];
                string hdType = context.Request.Params["hdType"];
              
               

                string headval = context.Request.Params["headval"];
                StringBuilder htmlbody = new StringBuilder();
                htmlbody.Append(context.Request.Params["bodyval"]);

                hdFileName = hdFileName + login.M_ID;

                htmlstr.Append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head>");
                htmlstr.Append(headval);
                htmlstr.Append("</head><body>");
                htmlstr.Append(htmlbody.ToString());
                htmlstr.Append("</body></html>");


                string path = context.Server.MapPath("../Temp/" + hdFileName + ".html");
                StreamWriter sw = new StreamWriter(path, false, System.Text.Encoding.GetEncoding("utf-8"));
                //写入到文件中 
                sw.Write(htmlstr.ToString());
                sw.Close();

                context.Response.Write("{'Result':'1','FileName':'" + hdFileName + "','Rooturl':'" + rooturl + "'}");
               
            }
        }



        private void sendMHTFile(HttpContext _context, string MHTString, string fileName, string Type)
        {


            _context.Response.Clear();
            _context.Response.ClearContent();
            _context.Response.ClearHeaders();
            _context.Response.Buffer = false;
            _context.Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            _context.Response.Expires = 0;
            _context.Response.AddHeader("Pragma", "No-Cache");
            _context.Response.AddHeader("Cache-Control", "Private");
            _context.Response.CacheControl = "No-Cache";

            //application/ms-excel
            if (Type.ToLower() == "xls")
                _context.Response.ContentType = "application/ms-excel;charset=utf-8";
            else if (Type.ToLower() == "doc")
                _context.Response.ContentType = "application/msword;charset=utf-8";

           

            _context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            _context.Response.Write(MHTString);
            _context.Response.End();
            _context.Response.Clear();
            _context.Response.Close();
        }

        private string convertWebPageToMHTString(string url)
        {

            CDO.MessageClass msg = new MessageClass();
            ADODB.Stream stm = null;
            string Rel = "";
            try
            {
                msg.MimeFormatted = true;
                CDO.Configuration c = new CDO.Configuration();
                msg.Configuration = c;


                msg.CreateMHTMLBody(url, CDO.CdoMHTMLFlags.cdoSuppressNone, "", "");

                stm = msg.GetStream();
                stm.Charset = "utf-8";
                Rel = stm.ReadText(stm.Size);
            }
            catch (Exception er) { }
            finally
            {
                if (stm != null) stm.Close();
            }
            return Rel;
        }

        loginInfo chklogin()
        {
            try
            {
                return SessionShard.loginUser;
            }
            catch
            {

                return null;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}